package com.zj.easytotwitter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zj.easytotwitter.activity.BaseActivity;
import com.zj.easytotwitter.event.DataEvent;
import com.zj.easytotwitter.fragment.BaseFragment;
import com.zj.easytotwitter.fragment.HomePageFragment;
import com.zj.easytotwitter.fragment.LookForStockFragment;
import com.zj.easytotwitter.fragment.MeFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * Created by ZJ on 2018/4/22 0022.
 * 主界面Activity
 */

public class MainActivty extends BaseActivity {
    public static int currentIndex;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private List<BaseFragment> fragments;
    private List<LinearLayout> menuLLs;
    private List<Integer> defaultImageViews;
    private List<Integer> selectedImageViews;

    @BindView(R.id.ll_homepage)
    LinearLayout llHomepage;
    @BindView(R.id.ll_find_stock)
    LinearLayout llFindStock;
    @BindView(R.id.ll_me)
    LinearLayout llMe;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initView() {
        defaultImageViews = Arrays.asList(new Integer[]{R.drawable.me_default, R.drawable.me_default, R.drawable.me_default});
        selectedImageViews = Arrays.asList(new Integer[]{R.drawable.me_checked, R.drawable.me_checked, R.drawable.me_checked});
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragments = new ArrayList<BaseFragment>();
        BaseFragment homePageFragment = new HomePageFragment();
        BaseFragment lookForStockFragment = new LookForStockFragment();
        BaseFragment meFragment = new MeFragment();
        fragments.add(homePageFragment);
        fragments.add(lookForStockFragment);
        fragments.add(meFragment);
        for (int i = 0; i < fragments.size(); i++) {
            fragmentTransaction.add(R.id.fl_fra, fragments.get(i));
        }
        fragmentTransaction.commit();
        menuLLs = new ArrayList<LinearLayout>();
        menuLLs.add(llHomepage);
        menuLLs.add(llFindStock);
        menuLLs.add(llMe);
        showFragment(currentIndex);
        setLitseners();
    }

    private void setLitseners() {
        for (int i = 0; i < menuLLs.size(); i++) {
            final int index = i;
            menuLLs.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentIndex = index;
                    showFragment(index);
                }
            });
        }
    }

    /**
     * 切换到指定的fragment并让对应菜单切换为选中状态
     *
     * @param index
     */
    public void showFragment(int index) {
        fragmentTransaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            LinearLayout ll = menuLLs.get(i);
            ImageView menuIV = (ImageView) ll.getChildAt(0);
            TextView menuTV = (TextView) ll.getChildAt(1);
            if (i == index) {
                fragmentTransaction.show(fragments.get(i));
                menuIV.setImageResource(selectedImageViews.get(i));
                menuTV.setTextColor(0xFF0093FF);
            } else {
                fragmentTransaction.hide(fragments.get(i));
                menuIV.setImageResource(defaultImageViews.get(i));
                menuTV.setTextColor(0xFFB3B3B3);
            }
        }
        fragmentTransaction.commit();
    }

    @Subscribe
    public void onEventMainThread(DataEvent event) {
        if (event.getPos()==9999){
            ShareUtils.share9PicsToWXCircle(this, "你好，成功的分享了多张照片到微信",paths);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        EventBus.getDefault().register(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //getLocalPis();
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //下载获取本地图片
    private File[] files;
    private List<String> paths = new ArrayList<String>();
    private final static String FILENAME="/sdcard/Test/";
    private void getLocalPis(){
        //ImageView image =(ImageView)findViewById(R.id.image);
        String path= Environment.getExternalStorageDirectory().getAbsolutePath();

        // 遍历 SD 卡下 .png 文件通过微信分享，保证SD卡根目录下有.png的文件
//        File root = Environment.getExternalStorageDirectory();
        File root = new File(path+"/sdcard/");

//        File destDir = new File(FILENAME); if (!destDir.exists()) { destDir.mkdirs();  }

        Bitmap abitmap = new BitmapFactory().decodeResource(getResources(), R.drawable.header_default);
        Bitmap bbitmap = new BitmapFactory().decodeResource(getResources(), R.drawable.header_default);
        //image.setImageBitmap(abitmap);
        File b = new File(path+"/sdcard/");
        if(!b.exists()){
            b.mkdirs();
        }

        try {
            File a = new File(path+"/sdcard/", "a.png");
            File bmap = new File(path+"/sdcard/", "b.png");
            if (!a.exists()) {
                a.createNewFile();
            }
            if(!b.exists()){
                bmap.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(a);
            FileOutputStream bout = new FileOutputStream(bmap);
            abitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            abitmap.compress(Bitmap.CompressFormat.PNG, 90, bout);
            out.flush();
            out.close();
            bout.flush();
            bout.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        files = root.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                //Toast.makeText(MainActivty.this, pathname.getName(), Toast.LENGTH_SHORT).show();
                if (pathname.getName().endsWith(".png"))
                    return true;
                return false;
            }
        });

        for(File file :files){
            paths.add(file.getAbsolutePath());
        }
    }
}
